package com.xzjt.common.utils;

import cn.hutool.core.date.DateUtil;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;

/**
 * @ClassName: DateUtils
 * @User: yuand
 * @Date: 2021/09/28 15:20
 * @Description: 日期工具类
 */
public class DateUtils {

    /**
     * 日期格式化
     *
     * @param date
     * @param format yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String format(Date date, String format) {
        if (null == date) {
            return "";
        }
        return DateUtil.format(date, format);
    }

    /**
     * 字符串转日期
     *
     * @param dateString
     * @param format
     * @return
     */
    public static Date parse(String dateString, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        if (null == dateString || "".equals(dateString)) {
            return null;
        }
        try {
            return sdf.parse(dateString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 日期字符串转Timestamp
     *
     * @param StrDate 必须为yyyy-mm-dd hh:mm:ss[.f...] 这样的格式，中括号表示可选，否则报错
     * @return
     */
    public static Timestamp formatTimestamp(String StrDate) {
        try {
            Timestamp ts = Timestamp.valueOf(StrDate);
            return ts;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前日期时间
     *
     * @param format
     * @return
     */
    public static String getNow(String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date());
    }

    /**
     * 将timestamp转为LocalDateTime
     *
     * @param timestamp
     * @return
     */
    public static LocalDateTime timestampToDatetime(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    /**
     * 将LocalDataTime转为timestamp
     *
     * @param localDateTime
     * @return
     */
    public static long datetimeToTimestamp(LocalDateTime localDateTime) {
        if (localDateTime == null)
            return 0;
        long timestamp = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        return timestamp;
    }

    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(timestampToDatetime(0));
        System.out.println();
        System.out.println(datetimeToTimestamp(null) + "||" + new Date().getTime());
    }

}
